import { contractAdd, contractDetail, contractUpdate, countryList } from "@/services/chargingManage";
import { getUuid } from "@/utils/utils";
import { Button, Cascader, DatePicker, Form, Icon, Input, message, Modal, Select } from "antd";
import moment from "moment";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
const dateFormat = 'YYYY-MM-DD'

class ContractModal extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      id:null,
      region:[[formatMessage({ id: 'contractModal.region.asia' }), formatMessage({ id: 'contractModal.region.china' })]],
      options:[]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initModal = id => {
    this.getCountryList()
    this.setState({
      id,
      visible:true
    },async () => {
      if(id){
        this.getDetail()
      }
    })
  }

  getCountryList = async () => {
    const res = await countryList()
    this.setState({options:res})
  }

  getDetail = async () => {
    const res = await contractDetail({id:this.state.id})
    this.props.form.setFieldsValue({
      name:res.name,
      times:[moment(res.startTime),moment(res.endTime)],
      signTime:moment(res.signTime),
      typeIds:res.typeIds,
    })
    this.setState({region:res.region})
  }

  doCancel = () => {
    this.props.form.resetFields()
    this.setState({
      visible:false,
      id:null,
      region:[["亚洲", "中国"]],
    })
  }

  okValidate = () => {
    if(this.props.readonly){
      this.doCancel()
      return false
    }
    this.props.form.validateFields(((error,values) => {
      if(!error){
        this.doSubmit(values)
      }
    }))
  }

  doSubmit = async values => {
    let res = {}
    const {times,...obj} = values;

    obj.startTime = values.times && values.times[0] ? moment(values.times[0]).format(dateFormat) : ''
    obj.endTime = values.times && values.times[1] ? moment(values.times[1]).format(dateFormat) : '' 
    obj.signTime = values.signTime ? moment(values.signTime).format(dateFormat) : '' 
    obj.region = this.state.region
    obj.enterpriseId = this.props.enterpriseId

    if(this.state.id){
      obj.id = this.state.id
      res = await contractUpdate(obj)
    }else{
      res = await contractAdd(obj)
    }

    if(res.code === -1){return false}

    message.info(res.message)
    this.doCancel()
    this.props.refreshList()
  }

  onChangeRegion = (value,index) => {
    let { region } = this.state
    region[index] = value;
    this.setState({region})
  }

  addItem = () => {
    let { region } = this.state
    region.push([])
    this.setState({region})
  }

  deleteItem = index => {
    let { region } = this.state
    const newList = region.filter((item,i) => i!= index)
    this.setState({region:newList})
  }

  render(){
    const { visible,region,options } = this.state;
    const { form:{getFieldDecorator},readonly } = this.props
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
    };
    return(
      <Modal
        title={formatMessage({ id: 'contractModal.title' })}
        visible={visible}
        onCancel={this.doCancel}
        onOk={this.okValidate}
        width={700}
      >
        <Form {...formItemLayout}>
          <Form.Item label={formatMessage({ id: 'contractModal.form.name' })}>
            {getFieldDecorator("name",{rules:[{required:true,message:formatMessage({ id: 'contractModal.form.pleaseInput' })}]})(
              <Input disabled={readonly} />
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'contractModal.form.timeRange' })}>
            {getFieldDecorator("times",{rules:[{required:true,message:formatMessage({ id: 'contractModal.form.pleaseSelect' })}]})(
              <DatePicker.RangePicker disabled={readonly} />
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'contractModal.form.signTime' })}>
            {getFieldDecorator("signTime",{rules:[{required:true,message:"请选择"}]})(
              <DatePicker disabled={readonly} />
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'contractModal.form.type' })}>
            {getFieldDecorator("typeIds",{rules:[{required:true,message:"请选择"}]})(
              <Select mode="multiple" disabled={readonly}>
                <Select.Option value={'0'}>{formatMessage({ id: 'contractModal.type.implementation' })}</Select.Option>
                <Select.Option value={'1'}>{formatMessage({ id: 'contractModal.type.development' })}</Select.Option>
                <Select.Option value={'2'}>{formatMessage({ id: 'contractModal.type.softwareDistribution' })}</Select.Option>
                <Select.Option value={'3'}>{formatMessage({ id: 'contractModal.type.softwareDirectSales' })}</Select.Option>
                <Select.Option value={'4'}>{formatMessage({ id: 'contractModal.type.operationMaintenance' })}</Select.Option>
              </Select>
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'contractModal.form.marketRegion' })}>
            {
              region.map((item,index) => {
                return (
                  <div style={{marginBottom:10}} key={getUuid()} >
                    <Cascader 
                      value={item} 
                      options={options} 
                      onChange={(value) => this.onChangeRegion(value,index)} 
                      placeholder={formatMessage({ id: 'contractModal.form.pleaseSelect' })}
                      style={{width:400,marginRight:10}} 
                      fieldNames={{ label: 'name', value: 'name' }}
                      disabled={readonly}
                    />
                    {
                      index === 0 ? <Button size="small" ghost type="primary" onClick={() => this.addItem()} disabled={readonly}>{formatMessage({ id: 'contractModal.button.add' })}</Button> : <Button size="small" ghost type="danger" onClick={() => this.deleteItem(index)} disabled={readonly}>{formatMessage({ id: 'contractModal.button.delete' })}</Button>
                    }
                    
                  </div>
                )
              })
            }
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(ContractModal)